package armazenador.ip;

import interfacedecomunicacao.LoginJaExistenteException;
import interfacedecomunicacao.UsuarioInexistenteException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import jogoBolaoeArmazenador.rn.Usuario;

public class IPUsuario {
	
	public Usuario autenticar(String login, char[] senha) throws UsuarioInexistenteException {
		
		String senhaString = "";
		for(int i = 0; i < senha.length; i++)
			senhaString += senha[i];
		
		String query = "SELECT * FROM usuario WHERE login ='" + login + "' AND senha = '" + senhaString + "'";
		
		Connection con = null;
		Statement stm = null;
		
		try {
			con = DriverManager.getConnection("jdbc:postgresql://localhost/senaonline","postgres", "bojador");
			stm = con.createStatement();
			
			ResultSet rs = stm.executeQuery(query);
			if(rs.next()){
				Usuario user = new Usuario(rs.getString("nome"), rs.getString("login"), rs.getString("senha"));
				return user;
			}else
				throw new UsuarioInexistenteException();
				
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally{
			
			try{
				stm.close();
				con.close();
			} catch (SQLException e){
				e.printStackTrace();
			}
		}
		
	}

	public boolean cadastraUsuario(Usuario novo) throws LoginJaExistenteException{
		
		Connection con = null;
		Statement stm = null;
		
		String query = "SELECT * FROM usuario WHERE usuario.login = '" + novo.get_login() + "'";
		
		try{
			con = DriverManager.getConnection("jdbc:postgresql://localhost/senaonline","postgres", "bojador");
			stm = con.createStatement();
			
			ResultSet rs = stm.executeQuery(query);
			if(rs.next())
				throw new LoginJaExistenteException();
		} catch(SQLException e){
			e.printStackTrace();
		}
		
		query = "INSERT INTO usuario (login, senha, nome) VALUES ('" + novo.get_login() + "', '" + novo.get_senha() + "', '" + novo.get_nome() + "')";
		
		try{
			
			con = DriverManager.getConnection("jdbc:postgresql://localhost/senaonline","postgres", "bojador");
			stm = con.createStatement();
			
			stm.executeUpdate(query);
			return true;
		} catch(SQLException e){
			e.printStackTrace();
			return false;
		} finally{
			
			try{
				stm.close();
				con.close();
			} catch(SQLException e){
				e.printStackTrace();
			}
			
		}
	}

}
